<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17
 * Time: 15:13
 * 后台管理员管理
 */

namespace app\admin\controller;

use app\admin\Base;
use app\admin\model\Operator as OperatorModel;
use app\admin\model\Roles;
use think\Db;

class Operator extends Base
{
    public function index()
    {
        $account = $this->request->param('account', '');
        $status = $this->request->param('status', '');
        $where = [];
        if(!empty($account)){
            $where['account']  = ['like',"%$account%"];
        }
        if($status != ''){
            $where['status'] = $status;
        }
        $model = new OperatorModel();
        $count = $model->where($where)->count();

        $list = $model->field('*')->order('create_time desc')->where($where)->paginate(20);
        if(!empty($list)){
            foreach($list as $k=>$v){
                $list[$k]['last_login_time'] = date("Y-m-d H:i:s", $list[$k]['last_login_time']);
                //此处需要优化！！！
                $role_ids = Db::name('role_operators')->where('operator_id' ,$list[$k]['id'])->column('role_id');
                $role_names = Db::name('roles')->whereIn('id', $role_ids)->column('name');
                $list[$k]['roles'] = implode('，', $role_names);
                unset($role_ids);
                unset($role_names);
            }
        }
        $page = $list->render();

        return $this->fetch('',compact('count', 'list', 'page'));
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\OperatorValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            //管理员相关数据
            $salt = getRandomString(6);
            $password = getDoubleMd5($data['password'], $salt);
            $data['password'] = $password;
            $data['salt'] = $salt;
            $data['email'] = $data['email'] ?? "";
            $data['phone'] = $data['phone'] ?? "";
            $data['remark'] = $data['remark'] ?? "";
            $data['last_login_time'] = time();
            $data['last_login_ip'] = $this->request->ip();
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['update_by'] = parent::$uid;
            //如果有选择角色
            $roles = isset($data['roles']) ? $data['roles'] : '';
            if (!empty($roles)) {
                foreach ($roles as $key => $value) {
                    //去空
                    if (empty($value)) {
                        unset($roles[$key]);
                    }
                }
                //验证角色是否存在
                $model = new Roles();
                if (!empty($roles)) {
                    $rs = $model->validateRoles($roles);
                    if (!$rs) {
                        return ajax_return_adv_error("所选角色不存在，请核查");
                    }
                }
                unset($data['roles']);
            }
            Db::startTrans();
            try {
                $uid = Db::name('operator')->insertGetId($data);
                if (!empty($roles)) {
                    foreach ($roles as $k => $v) {
                        $list[$k]['role_id'] = $v;
                        $list[$k]['operator_id'] = $uid;
                    }
                    Db::name('role_operators')->insertAll($list);
                }
                // 提交事务
                Db::commit();
                return ajax_return_adv("添加成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error("添加失败");
            }
        } else {
            // 添加页面
            $model = new Roles();
            $roles = $model->getAllRoles();

            return $this->fetch('', compact('roles'));
        }
    }

    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\OperatorValidate');
            if (!$validate->scene('edit')->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            if(!empty($data['password'])){
                $salt = getRandomString(6);
                $password = getDoubleMd5($data['password'], $salt);
                $data['password'] = $password;
                $data['salt'] = $salt;
            }else{
                unset($data['password']);
            }
            //管理员相关数据
            $data['email'] = $data['email'] ?? "";
            $data['phone'] = $data['phone'] ?? "";
            $data['remark'] = $data['remark'] ?? "";
            $data['last_login_time'] = time();
            $data['last_login_ip'] = $this->request->ip();
            $data['update_time'] = time();
            $data['update_by'] = parent::$uid;
            //如果有选择角色
            $roles = isset($data['roles']) ? $data['roles'] : '';
            if(!empty($roles)){
                foreach($roles as $key=>$value){
                    //去空
                    if(empty($value)){
                        unset($roles[$key]);
                    }
                }
                //验证角色是否存在
                $model = new Roles();
                if(!empty($roles)){
                    $rs = $model->validateRoles($roles);
                    if(!$rs){
                        return ajax_return_adv_error("所选角色不存在，请核查");
                    }
                }
                unset($data['roles']);
            }
            Db::startTrans();
            try{
                //修改管理员表
                Db::name('operator')->where('id', $data['id'])->update($data);

                //角色-用户关系表先删除再添加记录
                Db::name('role_operators')->where('operator_id', $data['id'])->delete();
                if(!empty($roles)){
                    foreach($roles as $k=>$v){
                        $list[$k]['role_id'] = $v;
                        $list[$k]['operator_id'] = $data['id'];
                    }
                    Db::name('role_operators')->insertAll($list);
                }
                // 提交事务
                Db::commit();
                return ajax_return_adv("编辑成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error("编辑失败");
            }
        } else {
            //获取角色信息
            $model = new Roles();
            $roles = $model->getAllRoles();
            //获取用户信息
            $id = $this->request->param('id',0);
            if(empty($id)){
                return ajax_return_adv_error("管理员id不能为空");
            }
            $model = new OperatorModel();
            $info = $model->get($id);
            //获取用户角色
            $user_roles = Db::name('role_operators')->where('operator_id', $id)->column('role_id');
            $user_roles = implode(',', $user_roles);
            return $this->fetch('', compact('roles', 'user_roles', 'info'));
        }
    }

    public function delete()
    {
        $id = $this->request->param('id',0);
        if(empty($id)){
            return ajax_return_adv_error("管理员id不能为空");
        }
        if(1 == $id){
            return ajax_return_adv_error("超级管理员不能删除！");
        }

        Db::startTrans();
        try{
            //删除管理员表
            Db::name('operator')->where('id', $id)->delete();

            //删除角色-用户关系表
            Db::name('role_operators')->where('operator_id', $id)->delete();
            // 提交事务
            Db::commit();
            return ajax_return_adv("删除成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_adv_error("删除失败");
        }
    }

    /**
     * @todo 授权角色
     */
    public function addRoles()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', '');
            $roles = $this->request->param('roles/a', '');
            if(empty($id)){
                return ajax_return_adv_error("管理员id不能为空！");
            }
            if (!empty($roles)) {
                foreach ($roles as $key => $value) {
                    //去空
                    if (empty($value)) {
                        unset($roles[$key]);
                    }
                }
                //验证角色是否存在
                $model = new Roles();
                if (!empty($roles)) {
                    $rs = $model->validateRoles($roles);
                    if (!$rs) {
                        return ajax_return_adv_error("所选角色不存在，请核查！");
                    }
                }
            }
            Db::startTrans();
            try{
                //角色-菜单关系表先删除再添加记录
                Db::name('role_operators')->where('operator_id', $id)->delete();
                if(!empty($roles)){
                    foreach($roles as $k=>$v){
                        $list[$k]['role_id'] = $v;
                        $list[$k]['operator_id'] = $id;
                    }
                    Db::name('role_operators')->insertAll($list);
                }
                // 提交事务
                Db::commit();
                return ajax_return_adv("授权角色成功！");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error("授权角色失败！");
            }
        } else {
            //获取角色信息
            $model = new Roles();
            $roles = $model->getAllRoles();
            //获取菜单信息
            $id = $this->request->param('id',0);
            if(empty($id)){
                return ajax_return_adv_error("管理员id不能为空");
            }
            $model = new OperatorModel();
            $info = $model->get($id);
            //获取管理员已有角色
            $role_menus = Db::name('role_operators')->where('operator_id', $id)->column('role_id');
            $role_menus = implode(',', $role_menus);
            return $this->fetch('',compact('info', 'roles', 'role_menus'));
        }
    }
}